package com.pwc.testing;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;

import com.google.common.base.Function;

public class SeleniumBaseAction {

	protected WebDriver driver;
	protected Actions action;
	protected LogUtil log;
	private Wait wait;

	public SeleniumBaseAction(WebDriver driver, LogUtil log) {
		this.driver = driver;
		this.action = new Actions(driver);
		this.log = log;
		this.wait=new FluentWait(driver)

				.withTimeout(30, TimeUnit.SECONDS)

				.pollingEvery(5, TimeUnit.SECONDS)

				.ignoring(NoSuchElementException.class);
	}
	



	protected List<WebElement> findElements(final String findType, final String element) {
		By by = null;
		
		List<WebElement> result = (List<WebElement>) wait.until(new Function<WebDriver,List<WebElement>>() {

			public List<WebElement> apply(WebDriver driver) {
				
				return findElementsNoWait(findType, element);
			}

		});
		
		
		return result;
	}
	
	private List<WebElement> findElementsNoWait(String findType, String element)
	{
		By by = null;
		if (FindType.BYID.equalsIgnoreCase(findType)) {
			by = By.id(element);
		} else if (FindType.BYNAME.equalsIgnoreCase(findType)) {
			by = By.name(element);
		} else if (FindType.BYXPATH.equalsIgnoreCase(findType)) {
			by = By.xpath(element);
		} else if (FindType.TAGNAME.equalsIgnoreCase(findType)) {
			by = By.tagName(element);
		} else if (FindType.CLASSNAME.equalsIgnoreCase(findType)) {
			by = By.className(element);
		} else if (FindType.CSSSELECTOR.equalsIgnoreCase(findType)) {
			by = By.cssSelector(element);
		} else if (FindType.LINKTEXT.equalsIgnoreCase(findType)) {
			by = By.linkText(element);
		} else if (FindType.PARTIALLINKTEXT.equalsIgnoreCase(findType)) {
			by = By.partialLinkText(element);
		} else {
			log.addLog("cannot find type: " + findType);
		}
		List<WebElement> temp = driver.findElements(by);
		if (temp.size() == 0) {
			log.addLog("cannot find element: " + element);
		}
		return driver.findElements(by);
	}

}
